package com.example.mysharding.config;

import com.example.mysharding.bean.ShardingProperties;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.lang.reflect.Method;


/**
 * @description: 分表数据源配置
 * @author: wangzihan
 * @time: 2023/08/21 18:43
 */
@AutoConfigureAfter(ShardingAutoConfigure.class)
@Configuration
//@MapperScan(basePackages = "com.example.demodal.mapper",
//        sqlSessionFactoryRef = "smartvisionDBSqlSessionFactory")
@EnableConfigurationProperties({ShardingProperties.class})
public class ShardingDBDataSourceConfig {

    @Autowired
    private ShardingAutoConfigure shardingAutoConfigure;

    @Autowired
    private ShardingProperties shardingProperties;

    // 多数据源必须将shardingjdbc数据源指定为主数据源,否则会报错
    @Primary
    @Bean(name = "shardingDataSourceS")
    DataSource createDataSource() throws Exception {
        Method createDataSource = ShardingAutoConfigure.class.getDeclaredMethod("createDataSource");
        createDataSource.setAccessible(true);
        return (DataSource) createDataSource.invoke(shardingAutoConfigure);
    }


    @Primary
    @Bean(name = "shardingSqlSessionFactory")
    public SqlSessionFactory db1SqlSessionFactory(@Qualifier("shardingDataSourceS") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(shardingProperties.getShardingMapperXml()));
        return bean.getObject();
    }

}



